package com.jdrx.sw.sewage.service;

import com.jdrx.platform.commons.rest.beans.dto.IdDTO;
import com.jdrx.platform.commons.rest.beans.vo.ResponseVO;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.commons.rest.factory.ResponseFactory2;
import com.jdrx.sw.sewage.beans.dto.NewsAddDTO;
import com.jdrx.sw.sewage.beans.entity.NewsPO;
import com.jdrx.sw.sewage.beans.vo.NewsVO;
import com.jdrx.sw.sewage.common.util.BeanUtils;
import com.jdrx.sw.sewage.dao.NewsDAO;
import com.jdrx.sw.sewage.service.base.BaseServiceImpl;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class NewsServiceImpl extends BaseServiceImpl {

    public static final Logger logger = LoggerFactory.getLogger(NewsServiceImpl.class);

    @Autowired
    private NewsDAO newsDAO;

    public ResponseVO add(NewsAddDTO newsAddDTO) throws BizException {
        Integer count = newsDAO.countNews();
        if (count >= 10) return ResponseFactory2.err("最大只支持10条新闻信息,删除新闻后再增加！");

//        Map<String,Object> mapPas = new HashMap<>();
//        mapPas.put("title",newsAddDTO.getTitle());
//        mapPas.put("newsContent","'" + newsAddDTO.getNewsContent() + "'");
//        mapPas.put("updateAt","'" + LocalDateTime.now() + "'");
//        mapPas.put("updateById",newsAddDTO.getUpdateById());
//        mapPas.put("updateBy",newsAddDTO.getUpdateBy());

        NewsPO po = new NewsPO();
        po.setUpdateAt(LocalDateTime.now());
        BeanUtils.copyProperties(newsAddDTO, po);
        po.setNewsContent(StringEscapeUtils.escapeHtml4(newsAddDTO.getNewsContent()));
        newsDAO.add(po);
        return ResponseFactory2.ok();
    }

    public void delete(IdDTO dto) {
        newsDAO.delete(dto);
    }

    public void update(NewsAddDTO newsAddDTO) {
        NewsPO po = new NewsPO();
        po.setUpdateAt(LocalDateTime.now());
        BeanUtils.copyProperties(newsAddDTO, po);
        po.setNewsContent(StringEscapeUtils.escapeHtml4(newsAddDTO.getNewsContent()));
        newsDAO.update(po);
    }

    public List<NewsVO> findList() {
        List<NewsVO> list = newsDAO.findList();
        list.forEach(item -> {
            item.setNewsContent(StringEscapeUtils.unescapeHtml4(item.getNewsContent()));
        });
        return list;
    }

    public NewsVO selectById(IdDTO dto) {
        return newsDAO.findById(dto);
    }
}
